/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gestionedt.modules;

import gestionedt.controllers.ModuleJpaController;
import gestionedt.controllers.PrestationJpaController;
import gestionedt.models.Module;
import gestionedt.models.Prestation;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;

/**
 * 
 */
public class SaveAction extends org.apache.struts.action.Action {
    
    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        if(isCancelled(request))
            return mapping.findForward("cancel");
        
        ModulesForm mForm = (ModulesForm) form;
        Module module = mForm.getModule();
        boolean nv = (module.getId()==null || module.getId() == 0);
        ModuleJpaController ctModule = new ModuleJpaController();
        if(nv)
            ctModule.create(module);
        else {
            Module m = ctModule.findModule(module.getId());
            m.setLibelle(module.getLibelle());
            m.setUe(module.getUe());
            m.setEffectifMax(module.getEffectifMax());
            m.setEstTermine(module.getEstTermine());
            if(m.getEstTermine()) {
                // si le module est terminé, toutes ses prestations sont enlevées de l'EDT
                PrestationJpaController ctPrest = new PrestationJpaController();
                for(Prestation p : m.getPrestations()) {
                    p.setCreneau(null);
                    ctPrest.edit(p);
                }
            }
            ctModule.edit(m);
        }

        return new ActionForward("/GererModules.do?action=afficher" +
                                         "&idModule="+module.getId()+
                                         "&sousFormStr="+mForm.getSousFormStr(), true);
    }

}
